package com.kl.oss.aws;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * @author kl liu
 * @description
 * @date 2021/8/27 10:51 上午
 */
@Slf4j
@Data
public class WiiAmazonManagerImpl implements WiiAmazonManager {

    private String endPoint;

    private String accessKey;

    private String secretKey;

    private String bucketName;

    private long expireTime = 3600000L;

    private AmazonS3 amazonS3;

    public WiiAmazonManagerImpl(String endPoint, String accessKey, String secretKey, String bucketName) {
        this.endPoint = endPoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
        init();
    }

    public WiiAmazonManagerImpl(String endPoint, String accessKey, String secretKey, String bucketName, long expireTime) {
        this.endPoint = endPoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
        this.expireTime = expireTime;
        init();
    }

    public void init() {
        log.info("start create s3Client");
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endPoint, Region.getRegion(Regions.CN_NORTH_1).getName());
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
        ClientConfiguration clientConfig = new ClientConfiguration();
        // 配置连接协议
        clientConfig.setProtocol(Protocol.HTTP);

        this.amazonS3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(clientConfig)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .withForceGlobalBucketAccessEnabled(true)
                .build();
        log.info("create s3Client success");
    }

    @Override
    public String preSignatureUrl(String objectKey) {
        // 设置预签名URL的过期时间
        Date expiration = new Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += expireTime;
        expiration.setTime(expTimeMillis);

        // 生成预签名URL
        log.info("开始生成预签名URL");
        GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucketName, objectKey)
                        .withMethod(HttpMethod.PUT)
                        .withExpiration(expiration);
        URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

    @Override
    public String downloadPath(String fileKey) {
        if (fileKey == null) {
            return null;
        }
        String download;
        try {
            if (StringUtils.isEmpty(fileKey)) {
                return null;
            }
            GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, fileKey);
            download = amazonS3.generatePresignedUrl(httpRequest).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return download;
    }

    @Override
    public AmazonFileModelResp upload(MultipartFile file, String fileKey) {
        AmazonFileModelResp amazonFileModelResp = new AmazonFileModelResp();
        // 文件类型和大小
        amazonFileModelResp.setFileType(file.getContentType());
        amazonFileModelResp.setFileSize(file.getSize());
        if (fileKey == null) {
            fileKey = System.currentTimeMillis() + file.getOriginalFilename();
        }
        log.info("fileKey={}", fileKey);
        amazonFileModelResp.setFileName(fileKey);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentLength(file.getSize());
        try {
            //String key = System.currentTimeMillis() + file.getOriginalFilename();
            // 配置文件访问权限
            amazonS3.putObject(new PutObjectRequest(bucketName, fileKey, file.getInputStream(), objectMetadata)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            // 文件访问路径
            String filePath = bucketName + "/" + fileKey;
            String url = endPoint + filePath;
            log.info("上传的图片地址={}", url);
            amazonFileModelResp.setFilePath(filePath);
            amazonFileModelResp.setUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return amazonFileModelResp;
    }

}
